package com.tdk.wifidirectserver.socket.client

import android.util.Log
import com.tdk.wifidirectserver.socket.SocketHandler
import java.io.IOException
import java.net.Socket
import java.nio.charset.Charset
import kotlin.math.log


/**
 * socket服务端管理类
 * @property TAG String
 * @property mServer ServerSocket? socket服务端
 * @property mIServerListener IServerActionListener? server回调接口
 * @property mAcceptThread AcceptThread? 轮询等待客户端连接的线程
 */
class ClientThread(
    private val client: Client,
    val iClientListener: IClientListener? = null,
) : Thread(), IClientAction {
    private var mSocketHandler: SocketHandler? = null
    val TAG = "ClientThread"
    override fun run() {
        Log.d(TAG, "ClientThread: ${currentThread().name}")
        try {
            val socket = Socket(client.ip, client.port!!)
            client.socket = socket
            iClientListener!!.onConnectSuccess()
            mSocketHandler =
                object : SocketHandler(client) {

                    override fun parseData(bytes: ByteArray?, client: Client) {
                        Log.d(TAG, "parseData:  ${String(bytes!!, Charset.defaultCharset())}")
                        iClientListener.parseData(bytes)
                    }

                    override fun disconnect(client: Client) {
                        iClientListener.onDisconnected()
                    }

                }
        } catch (e: Exception) {
            Log.e(TAG, "connect:exception:[$e] ")
            iClientListener!!.onConnectFailure()
        }
    }

    fun sendData(data: String?) {
        data?.toByteArray(Charset.defaultCharset())?.let {
            Log.d(TAG, "sendData: $it  mSocketHandler = $mSocketHandler")
            sendData(it)

        }
    }

    override fun sendData(data: ByteArray?) {
        data?.let {
            Log.d(TAG, "sendData: $it  mSocketHandler = $mSocketHandler")
            mSocketHandler?.putOutMessage(it)
        }
    }

    override fun disconnect() {
        mSocketHandler?.finish()
        mSocketHandler?.disconnect(client)
    }


}